from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import HttpResponse
import json
from .models import AdSchool, AdSchoolLabel, AdSchoolZan
from django.core.paginator import Paginator
from django.db.models import Q, F
import datetime
from django.contrib.auth.models import AnonymousUser
# Create your views here.
import math
@csrf_exempt
def showAdSchool(request):
    result = {}
    result['labelID'] = 0
    result['labelTitle'] = '产品运营'
    return render(request, 'html/main/article_item.html', result)

@csrf_exempt
def showArticleByTab(request, pk):
    result = {}
    try:
        ad = AdSchoolLabel.objects.get(id=pk)
        result['labelID'] = ad.id
        result['labelTitle'] = ad.ad_school_label
        return render(request, 'html/main/article_item.html', result)
    except Exception as e:
        print(e)
        result['labelID'] = 0
        result['labelTitle'] = '产品运营'
        return render(request, 'html/main/article_item.html', result)

@csrf_exempt
def showArticle(request, pk):
    try:
        adS = AdSchool.objects.get(id=pk)
        AdSchool.objects.filter(id=pk).update(ad_school_count=F('ad_school_count') + 1, ad_school_browse_time=datetime.datetime.now())
        result = {}
        result['contentDetails'] = {}
        result['contentDetails']['id'] = adS.id
        result['contentDetails']['ad_school_title'] = adS.ad_school_title
        result['contentDetails']['ad_school_count'] = adS.ad_school_count
        result['contentDetails']['ad_school_article'] = adS.ad_school_article
        result['contentDetails']['ad_school_laud'] = adS.ad_school_laud
        result['contentDetails']['ad_school_count_time'] = getCountTime(adS.ad_school_create_time)
        result['contentDetails']['ad_school_label'] = adS.ad_school_label.ad_school_label
        result['contentDetails']['ad_school_label_id'] = adS.ad_school_label.id
        result['contentDetails']['ad_school_auth'] = adS.ad_school_auth
        result['contentDetails']['ad_school_image'] = '/imagethinking_school/' + str(adS.ad_school_image)
        return render(request, 'html/main/article_article.html', result)
    except Exception as e:
        print(e)
        result = {}
        result['contentDetails'] = {}
        result['contentDetails']['id'] = 0
        result['contentDetails']['ad_school_title'] = '无相关标题'
        result['contentDetails']['ad_school_count'] = 0
        result['contentDetails']['ad_school_article'] = '无相关文章'
        result['contentDetails']['ad_school_laud'] = 0
        result['contentDetails']['ad_school_count_time'] = '0分钟前'
        result['contentDetails']['ad_school_label'] = '产品运营'
        result['contentDetails']['ad_school_label_id'] = 0
        result['contentDetails']['ad_school_auth'] = '无'
        result['contentDetails']['ad_school_image'] = '../../../static/images/aside_ad.jpg'
        return render(request, 'html/main/article_article.html', result)

@csrf_exempt
def showAllLabel(request):
    '''
    显示所有热门标签
    :param request:
    :return:
    '''
    response = {'labelData': []}
    all_label = AdSchoolLabel.objects.all().order_by('-create_time')
    if all_label.exists():
        for asset in all_label:
            response['labelData'].append({
                "id": asset.id,
                "ad_school_label": asset.ad_school_label if asset.ad_school_label else "",
            })
    return HttpResponse(json.dumps(response))

@csrf_exempt
def getNewArticle(request):
    '''
    获取最新的8篇文章
    :param request:
    :return:
    '''
    response = {'newArticle': []}
    all_new_article = AdSchool.objects.filter(~Q(ad_school_label=None)).order_by('-ad_school_create_time')[0:8]
    if all_new_article.exists():
        for asset in all_new_article:
            response['newArticle'].append({
                "id": asset.id if asset.id else "",
                "ad_school_title": str(asset.ad_school_title)[0:20] if asset.ad_school_title else "",
                "ad_school_article": asset.ad_school_article if asset.ad_school_article else "",
                "ad_school_image": '/imagethinking_school/'+str(asset.ad_school_image) if asset.ad_school_image else "",
                "ad_school_count": asset.ad_school_count,
                "ad_school_create_time": str(asset.ad_school_create_time.year) + '年' + str(asset.ad_school_create_time.month) + '月' + str(asset.ad_school_create_time.day) + '日'
            })
    return HttpResponse(json.dumps(response), content_type='application/json')



@csrf_exempt
def getAdSchoolInfo(request):
        if request.method == "GET":
            limit = request.GET.get('limit')   # how many items per page
            offset = request.GET.get('offset')  # how many items in total in the DB
            labelSearch = request.GET.get('labelSearch')
            # sort_column = request.GET.get('sort')   # which column need to sort
            # order = request.GET.get('order')      # ascending or descending
            if labelSearch and labelSearch != '0':    #    判断是否有搜索字
                all_records = AdSchool.objects.filter(Q(ad_school_label_id=int(labelSearch)), ~Q(ad_school_label=None)).order_by('-ad_school_create_time', '-ad_school_count')
            else:
                all_records = AdSchool.objects.filter(~Q(ad_school_label=None)).order_by('-ad_school_create_time', '-ad_school_count')
            if all_records.exists():
                all_records_count = all_records.count()
                if not offset:
                    offset = 1
                if not limit:
                    limit = 20    # 默认是每页20行的内容，与前端默认行数一致
                try:
                    pageinator = Paginator(all_records, limit)   # 开始做分页
                    page = offset
                    response_data = {'total': all_records_count, 'rows': []}   # 必须带有rows和total这2个key，total表示总页数，rows表示每行的内容
                    for asset in pageinator.page(page):
                        response_data['rows'].append({
                            "id": asset.id if asset.id else "",
                            "ad_school_title": asset.ad_school_title if asset.ad_school_title else "",
                            "ad_school_image": '/imagethinking_school/' + str(asset.ad_school_image),
                            "ad_school_count": asset.ad_school_count,
                            "ad_school_article": str(filterHtmlTab(asset.ad_school_article))[0:100]+'...' if asset.ad_school_article else "",
                            'ad_school_label': asset.ad_school_label.ad_school_label,
                            'ad_school_label_id': asset.ad_school_label.id,
                            'ad_school_count_time': getCountTime(asset.ad_school_create_time)
                        })

                    return HttpResponse(json.dumps(response_data))    # 需要json处理下数据格式
                except Exception as e:
                    print(e)
                    response_data = {'total': 0, 'rows': []}
                    return HttpResponse(json.dumps(response_data))
            else:
                response_data = {'total': 0, 'rows': []}
                return HttpResponse(json.dumps(response_data))

def filterHtmlTab(htmlStr):
    '''
    过滤html标签
    :param htmlStr:
    :return:
    '''
    import re
    dr = re.compile(r'<[^>]+>', re.S)
    newHtmlStr = dr.sub('', htmlStr)
    return newHtmlStr

def getCountTime(startTime):
    '''
    计算时间
    :param startTime:
    :return:
    '''
    endTime = datetime.datetime.now()
    trueTime = endTime - startTime
    seconds = trueTime.seconds + trueTime.days * 60 * 60 * 24
    if seconds > 0 and seconds < 60*60:
        return str(math.ceil(seconds / 60))+'分钟前'
    elif seconds >= 60*60 and seconds < 60*60*24:
        return str(math.ceil(seconds / (60*60)))+'小时前'
    elif seconds >= 60*60*24 and seconds < 60*60*24*7:
        return str(math.ceil(seconds / (60*60*24)))+'天前'
    elif seconds >= 60*60*24*7:
        return str(startTime.year)+'年'+str(startTime.month)+'月'+str(startTime.day)+'日'
    elif seconds <= 0:
        return '无记录'
from django.http import JsonResponse
@csrf_exempt
def handleZan(request, pk):
    response = {}
    AdSchool.objects.filter(id=pk).update(ad_school_laud=F('ad_school_laud') + 1, ad_school_update_time=datetime.datetime.now())
    user = request.user
    try:
        AdSchool.objects.get(id=pk)
        if user == AnonymousUser:
            AdSchoolZan.objects.create(article_id=pk, user=AnonymousUser, create_time=datetime.datetime.now())
        else:
            AdSchoolZan.objects.create(article_id=pk, user_id=user.id, create_time=datetime.datetime.now())
    except Exception as e:
        print(e)

    response['code'] = 200
    return JsonResponse(response)

